﻿using JESAI.Application.Abstractions.Admin;
using JESAI.Application.Abstractions.Admin.Dtos.Dict;
using JESAI.Application.Abstractions.Admin.Dtos.Post;
using JESAI.Application.Abstractions.Dtos;
using JESAI.AutoMapper.ObjectMapping;
using JESAI.Core;
using JESAI.Core.Attributes;
using JESAI.Core.Extensions;
using JESAI.Core.Util.Helpers;
using JESAI.Platform.Domain.Admin.Repositories;
using JESAI.Platform.Domain.Sys.Entities;
using JESAI.Platform.Domain.Sys.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Application.Service.Admin
{
    [AppService]
    internal class PostService : IPostService
    {
        private readonly IPostRepository _postRepository;
        private readonly IUser _user;
        public PostService(IPostRepository postRepository, IUser user)
        {
            _postRepository = postRepository;
            _user = user;
        }

        public async Task DeletePost(string id)
        {
            await _postRepository.DeleteByIdAsync(id);
        }

        public async Task DeletePosts(string[] ids)
        {
            await _postRepository.DeleteByIdsAsync(ids);
        }

        public async Task<BasePageOutput<List<QueryPostDto>>> QueryPagePosts(QueryPostPageInput input)
        {
            var totalNumber = 0;
            var modelList = _postRepository._DbQueryable
                               .WhereIF(input.IsValid.HasValue, it => it.IsValid == input.IsValid)
                               .WhereIF(!input.Name.IsEmpty(), it => it.Name == input.Name)
                               .WhereIF(!input.Code.IsEmpty(), it => it.Code == input.Code)
                               .ToPageList(input.PageIndex, input.PageSize, ref totalNumber);

            return new BasePageOutput<List<QueryPostDto>> { Data = modelList.MapTo<List<QueryPostDto>>(), CurrentPage = input.PageIndex, Total = totalNumber };
        }

        public async Task UpdateOrInsert(SetPostInput input)
        {
            var model = input.MapTo<PostEntity>();
            if (model.Id.IsNullOrEmpty())
            {
                model.Id = Guid.NewGuid().ToString();
                model.CreateTime = DateTime.Now;
                model.Cid = _user.Id.ToLong();
                await _postRepository.InsertAsync(model);
            }
            else
            {
                model.UpdateTime = DateTime.Now;
                model.Uid = _user.Id.ToLong();
                await _postRepository.UpdateAsync(model);
            }
        }
    }
}
